<!--
 * @copyright 2025 银杏ERP
 * @author 银杏ERP
 * @version 1.0
 * @license http://www.hhyx.xyz
 * @developer Lhf
-->

<template>
    <el-card shadow="hover" class="warehouse-capacity-card">
        <template #header>
            <div class="card-header">
                <div class="title-with-icon">
                    <Icon name="fa fa-database" class="title-icon" />
                    <span>{{ t('仓库容量') }}</span>
                </div>
                <div class="header-actions">
                    <el-button link type="primary" @click="refreshData">
                        <Icon name="fa fa-refresh" />
                    </el-button>
                </div>
            </div>
        </template>
        <div v-loading="loading" class="capacity-container">
            <template v-if="!showDetail">
                <div class="summary-view">
                    <div class="total-info">
                        <div class="total-item">
                            <div class="label">{{ t('总容量') }}</div>
                            <div class="value">{{ totalCapacity }} m<sup>3</sup></div>
                        </div>
                        <div class="total-item">
                            <div class="label">{{ t('已使用') }}</div>
                            <div class="value">{{ usedCapacity }} m<sup>3</sup></div>
                        </div>
                        <div class="total-item">
                            <div class="label">{{ t('使用率') }}</div>
                            <div class="value">{{ usageRate }}%</div>
                        </div>
                    </div>
                    <div ref="overallProgressRef" class="overall-progress">
                        <div class="progress-info">
                            <div class="progress-label">{{ t('总体使用率') }}</div>
                            <div class="progress-value">{{ usageRate }}%</div>
                        </div>
                    </div>
                </div>
                
                <div class="warehouses-grid">
                    <div v-for="warehouse in warehouseList" :key="warehouse.id" class="warehouse-item">
                        <div class="warehouse-info">
                            <div class="warehouse-name">{{ warehouse.name }}</div>
                            <div class="warehouse-usage" :class="getUsageClass(warehouse.usageRate)">
                                {{ warehouse.usageRate }}%
                            </div>
                        </div>
                        <el-progress 
                            :percentage="warehouse.usageRate" 
                            :color="getProgressColor(warehouse.usageRate)"
                            :striped="warehouse.usageRate > 90"
                            :striped-flow="warehouse.usageRate > 90"
                            :stroke-width="8"
                        />
                        <div class="capacity-details">
                            <div class="detail-item">
                                <span class="label">{{ t('总容量') }}:</span>
                                <span class="value">{{ warehouse.capacity }} m<sup>3</sup></span>
                            </div>
                            <div class="detail-item">
                                <span class="label">{{ t('已使用') }}:</span>
                                <span class="value">{{ warehouse.used }} m<sup>3</sup></span>
                            </div>
                        </div>
                    </div>
                </div>
                
                <div class="view-detail">
                    <el-button link type="primary" @click="showDetail = true">
                        {{ t('查看详细数据') }} <Icon name="fa fa-angle-right" />
                    </el-button>
                </div>
            </template>
            
            <template v-else>
                <div class="detail-view">
                    <div class="table-actions">
                        <el-input
                            v-model="searchKeyword"
                            :placeholder="t('搜索仓库名称')"
                            prefix-icon="el-icon-Search"
                            clearable
                            size="small"
                            class="search-input"
                        />
                        <el-select
                            v-model="filterStatus"
                            :placeholder="t('使用率筛选')"
                            clearable
                            size="small"
                        >
                            <el-option label="紧张 (>90%)" value="critical" />
                            <el-option label="较高 (70-90%)" value="high" />
                            <el-option label="适中 (40-70%)" value="medium" />
                            <el-option label="宽松 (<40%)" value="low" />
                        </el-select>
                    </div>
                    
                    <el-table :data="filteredWarehouseData" size="small" style="width: 100%">
                        <el-table-column prop="name" :label="t('仓库名称')" min-width="120" />
                        <el-table-column prop="address" :label="t('位置')" min-width="120" show-overflow-tooltip />
                        <el-table-column prop="capacity" :label="t('总容量 (m³)')" width="100" align="right" />
                        <el-table-column prop="used" :label="t('已使用 (m³)')" width="100" align="right" />
                        <el-table-column :label="t('使用率')" width="180">
                            <template #default="scope">
                                <div class="usage-cell">
                                    <el-progress
                                        :percentage="scope.row.usageRate"
                                        :color="getProgressColor(scope.row.usageRate)"
                                        :striped="scope.row.usageRate > 90"
                                        :striped-flow="scope.row.usageRate > 90"
                                        :stroke-width="6"
                                        :text-inside="true"
                                    />
                                </div>
                            </template>
                        </el-table-column>
                        <el-table-column :label="t('状态')" width="100">
                            <template #default="scope">
                                <el-tag
                                    :type="getStatusTagType(scope.row.usageRate)"
                                    size="small"
                                    effect="light"
                                >
                                    {{ getStatusText(scope.row.usageRate) }}
                                </el-tag>
                            </template>
                        </el-table-column>
                    </el-table>
                    
                    <div class="back-to-summary">
                        <el-button link type="primary" @click="showDetail = false">
                            <Icon name="fa fa-angle-left" /> {{ t('返回概览') }}
                        </el-button>
                    </div>
                </div>
            </template>
        </div>
    </el-card>
</template>

<script setup lang="ts">
import { ref, onMounted, computed, nextTick } from 'vue'
import { useI18n } from 'vue-i18n'
import * as echarts from 'echarts/core'
import { GaugeChart } from 'echarts/charts'
import { TitleComponent, TooltipComponent } from 'echarts/components'
import { CanvasRenderer } from 'echarts/renderers'
import Icon from '/@/components/icon/index.vue'

// 注册 ECharts 必须的组件
echarts.use([TitleComponent, TooltipComponent, GaugeChart, CanvasRenderer])

const { t } = useI18n()
const loading = ref(false)
const showDetail = ref(false)
const overallProgressRef = ref<HTMLElement | null>(null)
let chart: echarts.ECharts | null = null
const searchKeyword = ref('')
const filterStatus = ref('')

// 计算总容量和使用率
const totalCapacity = ref(15500)
const usedCapacity = ref(9850)
const usageRate = computed(() => {
    return Math.round((usedCapacity.value / totalCapacity.value) * 100)
})

// 仓库数据
const warehouseList = ref([
    {
        id: 1,
        name: '总仓',
        address: '上海市浦东新区张江高科技园区',
        capacity: 5000,
        used: 3750,
        usageRate: 75
    },
    {
        id: 2,
        name: '北京仓',
        address: '北京市海淀区中关村科技园',
        capacity: 3500,
        used: 3150,
        usageRate: 90
    },
    {
        id: 3,
        name: '广州仓',
        address: '广州市天河区珠江新城',
        capacity: 2500,
        used: 1500,
        usageRate: 60
    },
    {
        id: 4,
        name: '成都仓',
        address: '成都市高新区天府大道',
        capacity: 2000,
        used: 700,
        usageRate: 35
    },
    {
        id: 5,
        name: '武汉仓',
        address: '武汉市东湖高新区光谷大道',
        capacity: 1500,
        used: 750,
        usageRate: 50
    },
    {
        id: 6,
        name: '深圳仓',
        address: '深圳市南山区科技园',
        capacity: 1000,
        used: 0,
        usageRate: 0
    }
])

// 筛选仓库数据
const filteredWarehouseData = computed(() => {
    return warehouseList.value.filter(warehouse => {
        // 关键词筛选
        if (searchKeyword.value && !warehouse.name.includes(searchKeyword.value) && !warehouse.address.includes(searchKeyword.value)) {
            return false
        }
        
        // 状态筛选
        if (filterStatus.value) {
            const rate = warehouse.usageRate
            if (filterStatus.value === 'critical' && rate <= 90) return false
            if (filterStatus.value === 'high' && (rate <= 70 || rate > 90)) return false
            if (filterStatus.value === 'medium' && (rate <= 40 || rate > 70)) return false
            if (filterStatus.value === 'low' && rate >= 40) return false
        }
        
        return true
    })
})

// 获取进度条颜色
const getProgressColor = (usageRate: number): string => {
    if (usageRate > 90) return '#F56C6C'
    if (usageRate > 70) return '#E6A23C'
    if (usageRate > 40) return '#409EFF'
    return '#67C23A'
}

// 获取使用率样式类
const getUsageClass = (usageRate: number): string => {
    if (usageRate > 90) return 'usage-critical'
    if (usageRate > 70) return 'usage-high'
    if (usageRate > 40) return 'usage-medium'
    return 'usage-low'
}

// 获取状态文本
const getStatusText = (usageRate: number): string => {
    if (usageRate > 90) return t('紧张')
    if (usageRate > 70) return t('较高')
    if (usageRate > 40) return t('适中')
    if (usageRate > 0) return t('宽松')
    return t('空置')
}

// 获取状态标签类型
const getStatusTagType = (usageRate: number): 'danger' | 'warning' | 'primary' | 'success' | 'info' => {
    if (usageRate > 90) return 'danger'
    if (usageRate > 70) return 'warning'
    if (usageRate > 40) return 'primary'
    if (usageRate > 0) return 'success'
    return 'info'
}

// 初始化仪表盘
const initGaugeChart = () => {
    if (!overallProgressRef.value) return
    
    if (chart) {
        chart.dispose()
    }
    
    chart = echarts.init(overallProgressRef.value)
    
    const option = {
        series: [
            {
                type: 'gauge',
                progress: {
                    show: true,
                    width: 18,
                    itemStyle: {
                        color: {
                            type: 'linear',
                            x: 0,
                            y: 0,
                            x2: 1,
                            y2: 0,
                            colorStops: [
                                { offset: 0, color: '#6BCEFF' },
                                { offset: 0.5, color: '#409EFF' },
                                { offset: 1, color: getProgressColor(usageRate.value) }
                            ]
                        }
                    }
                },
                axisLine: {
                    lineStyle: {
                        width: 18,
                        color: [[1, '#E9EDF5']]
                    }
                },
                axisTick: {
                    show: false
                },
                splitLine: {
                    show: false
                },
                axisLabel: {
                    distance: 25,
                    color: '#999',
                    fontSize: 12,
                    formatter: (value: number) => {
                        if (value === 0) return '0%'
                        if (value === 50) return '50%'
                        if (value === 100) return '100%'
                        return ''
                    }
                },
                anchor: {
                    show: true,
                    showAbove: true,
                    size: 20,
                    itemStyle: {
                        borderWidth: 3,
                        borderColor: '#fff',
                        color: getProgressColor(usageRate.value)
                    }
                },
                pointer: {
                    show: false
                },
                detail: {
                    show: false
                },
                data: [{ value: usageRate.value }]
            }
        ]
    }
    
    chart.setOption(option)
}

// 刷新数据
const refreshData = () => {
    loading.value = true
    
    // 模拟数据刷新过程
    setTimeout(() => {
        // 随机调整使用量
        warehouseList.value = warehouseList.value.map(warehouse => {
            const adjustment = Math.random() * 10 - 5 // -5% 到 +5% 的随机调整
            const newUsageRate = Math.max(0, Math.min(100, Math.round(warehouse.usageRate + adjustment)))
            const newUsed = Math.round(warehouse.capacity * newUsageRate / 100)
            return { ...warehouse, usageRate: newUsageRate, used: newUsed }
        })
        
        // 重新计算总使用量
        usedCapacity.value = warehouseList.value.reduce((sum, warehouse) => sum + warehouse.used, 0)
        
        // 重新初始化仪表盘
        if (!showDetail.value) {
            nextTick(() => {
                initGaugeChart()
            })
        }
        
        loading.value = false
    }, 600)
}

// 监听详情视图切换
const handleViewChange = () => {
    if (!showDetail.value) {
        nextTick(() => {
            initGaugeChart()
        })
    }
}

// 组件挂载完成后初始化
onMounted(() => {
    loading.value = true
    
    // 模拟加载数据
    setTimeout(() => {
        initGaugeChart()
        loading.value = false
    }, 600)
})
</script>

<style scoped lang="scss">
.warehouse-capacity-card {
    height: 360px;
    margin-bottom: 20px;
    
    .card-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        
        .title-with-icon {
            display: flex;
            align-items: center;
            
            .title-icon {
                color: #409EFF;
                margin-right: 8px;
                font-size: 16px;
            }
        }
        
        .header-actions {
            display: flex;
            align-items: center;
        }
    }
    
    .capacity-container {
        height: 280px;
        
        .summary-view {
            display: flex;
            margin-bottom: 20px;
            
            .total-info {
                display: flex;
                flex: 1;
                
                .total-item {
                    flex: 1;
                    text-align: center;
                    
                    .label {
                        font-size: 12px;
                        color: #909399;
                        margin-bottom: 5px;
                    }
                    
                    .value {
                        font-size: 20px;
                        font-weight: bold;
                        color: #303133;
                    }
                }
            }
            
            .overall-progress {
                width: 150px;
                height: 80px;
                position: relative;
                
                .progress-info {
                    position: absolute;
                    bottom: 2px;
                    width: 100%;
                    text-align: center;
                    
                    .progress-label {
                        font-size: 12px;
                        color: #909399;
                    }
                    
                    .progress-value {
                        font-size: 20px;
                        font-weight: bold;
                        color: #409EFF;
                    }
                }
            }
        }
        
        .warehouses-grid {
            display: grid;
            grid-template-columns: repeat(6, 1fr);
            gap: 15px;
            
            .warehouse-item {
                background-color: #f8f9fa;
                border-radius: 8px;
                padding: 12px;
                
                .warehouse-info {
                    display: flex;
                    justify-content: space-between;
                    align-items: center;
                    margin-bottom: 8px;
                    
                    .warehouse-name {
                        font-weight: bold;
                        font-size: 14px;
                        color: #303133;
                    }
                    
                    .warehouse-usage {
                        font-size: 14px;
                        font-weight: bold;
                        
                        &.usage-critical {
                            color: #F56C6C;
                        }
                        
                        &.usage-high {
                            color: #E6A23C;
                        }
                        
                        &.usage-medium {
                            color: #409EFF;
                        }
                        
                        &.usage-low {
                            color: #67C23A;
                        }
                    }
                }
                
                .capacity-details {
                    margin-top: 8px;
                    display: flex;
                    font-size: 12px;
                    color: #606266;
                    
                    .detail-item {
                        margin-right: 15px;
                        
                        .label {
                            color: #909399;
                            margin-right: 5px;
                        }
                    }
                }
            }
        }
        
        .view-detail {
            text-align: center;
            margin-top: 15px;
        }
        
        .detail-view {
            height: 100%;
            display: flex;
            flex-direction: column;
            
            .table-actions {
                display: flex;
                margin-bottom: 10px;
                gap: 10px;
                
                .search-input {
                    width: 200px;
                }
            }
            
            .usage-cell {
                padding: 2px 0;
            }
            
            .back-to-summary {
                margin-top: 10px;
            }
        }
    }
}

@media screen and (max-width: 1600px) {
    .warehouse-capacity-card {
        .capacity-container {
            .warehouses-grid {
                grid-template-columns: repeat(3, 1fr);
            }
        }
    }
}

@media screen and (max-width: 1200px) {
    .warehouse-capacity-card {
        .capacity-container {
            .warehouses-grid {
                grid-template-columns: repeat(2, 1fr);
            }
        }
    }
}

@media screen and (max-width: 768px) {
    .warehouse-capacity-card {
        height: auto;
        
        .capacity-container {
            height: auto;
            
            .summary-view {
                flex-direction: column;
                
                .overall-progress {
                    width: 100%;
                    margin-top: 15px;
                }
            }
            
            .warehouses-grid {
                grid-template-columns: 1fr;
            }
        }
    }
}
</style> 